package gold.digger;

import gold.utils.InputUtil;
import gold.vo.TreeNode;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LCJZOF051 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        Map<TreeNode, Integer> memo = new HashMap<>();
        int ans = Integer.MIN_VALUE;

        public int maxPathSum(TreeNode root) {
            dfsRootToBottomMax(root);
            dfsMaxPathSum(root);
            return ans;
        }

        // get max path sum.
        public void dfsMaxPathSum(TreeNode root) {
            if (null == root) return;

            int leftSide = Math.max(memo.getOrDefault(root.left, 0), 0);
            int rightSide = Math.max(memo.getOrDefault(root.right, 0), 0);
            int curAns = leftSide + rightSide + root.val;
            ans = Math.max(ans, curAns);
            dfsMaxPathSum(root.left);
            dfsMaxPathSum(root.right);
        }

        // get from current root ( including ) to children node max path, not necessary to leaf node.
        public int dfsRootToBottomMax(TreeNode root) {
            if (null == root) return 0;
            if (memo.containsKey(root)) return memo.get(root);

            int leftSide = dfsRootToBottomMax(root.left);
            int rightSide = dfsRootToBottomMax(root.right);
            int curMaxToBottom = Math.max(Math.max(leftSide, rightSide), 0) + root.val;
            memo.put(root, curMaxToBottom);
            return curMaxToBottom;
        }
    }

    public void run() {
        System.out.println(new Solution().maxPathSum(TreeNode.createTree("[2,-1]")));
        System.out.println(new Solution().maxPathSum(TreeNode.createTree("[-3]")));
        System.out.println(new Solution().maxPathSum(TreeNode.createTree("[1,2,3]")));
        System.out.println(new Solution().maxPathSum(TreeNode.createTree("[-10,9,20,null,null,15,7]")));
    }

    public static void main(String[] args) throws Exception {
        LCJZOF051 an = new LCJZOF051();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
